﻿using Core;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

public class ExportAnimConf
{
    private static readonly Dictionary<string, Dictionary<EDir4, SortedList<int, Sprite>>> SpriteDict = new();

    [MenuItem("Assets/Mini Tools/Texture/导出 Anim Conf", false, 301)]
    private static void Main()
    {
        EditorUtils.ForeachTexture(ProcessTexture);

        AssetDatabase.SaveAssets(); //存储资源
        AssetDatabase.Refresh(); //刷新

        Debug.Log("处理完成");
    }

    private static void GetSprites(string path)
    {
        SpriteDict.Clear();

        var sprites = AssetDatabase.LoadAllAssetsAtPath(path);

        foreach (var obj in sprites)
        {
            if (obj is not Sprite sprite) continue;

            var strArr = sprite.name.Split('_');
            if (strArr.Length != 3) continue;

            Debug.Log(sprite.name);
            var dir = Utils.Dir.Get4(strArr[1]);
            if (dir == EDir4.Invalid) continue;

            if (int.TryParse(strArr[2], out var idx) == false)
            {
                continue;
            }

            var action = strArr[0];

            if (SpriteDict.ContainsKey(action) == false)
            {
                var d = new Dictionary<EDir4, SortedList<int, Sprite>>
                {
                    [EDir4.Up] = new(),
                    [EDir4.Down] = new(),
                    [EDir4.Left] = new(),
                    [EDir4.Right] = new()
                };

                SpriteDict[action] = d;
            }

            var dd = SpriteDict[action];
            var lst = dd[dir];
            lst.Add(idx, sprite);
        }
    }

    private static void ProcessTexture(TextureImporter importer, string path)
    {
        Debug.Log($"Process...  path={path}");
        var parser = new PathParser(path);

        var rootPath = parser.DirectoryName;

        GetSprites(path);

        foreach (var pair in SpriteDict)
        {
            var conf = ScriptableObject.CreateInstance<Core.Anim4DirData>();

            conf.AnimName = pair.Key;

            var len = pair.Value.Count;
            conf.animPerDir = new Core.Anim4DirData.Anim[len];
            int i = 0;
            foreach (var pair2 in pair.Value)
            {
                conf.animPerDir[i] = new Core.Anim4DirData.Anim();
                var item = conf.animPerDir[i];
                item.Dir = pair2.Key;
                item.Sprites = pair2.Value.Values.ToArray();
                i++;
            }

            AssetDatabase.CreateAsset(conf, $"{rootPath}/{pair.Key}.asset");
        }
    }
}